package com.nyist.threadCase3;

import com.alibaba.fastjson.JSONObject;
import com.nyist.thread.NyistThreadUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 1.
 *
 * @ClassName RedBus
 * @Description
 * @Author xiaoyang
 * @Date 2023/04/09/17:50
 */
@Slf4j
public class RedBus implements Runnable {

    Lock lock = new ReentrantLock();

    private final Map<Integer, Integer> moneyMap;

    public RedBus(Map<Integer, Integer> moneyMap) {
        this.moneyMap = moneyMap;
    }

    public static void main(String[] args) {
        int money = 100;
        int redNum = 3;

        Map<Integer, Integer> moneyMap = new HashMap<>(redNum);

        Random random = new Random();

        int createMoney;
        int numberOfRandomCalculations = redNum - 1;
        for (int i = 0; i < numberOfRandomCalculations; i++) {
            // 随机生成的钱
            createMoney = random.nextInt(money);
            // 剩余的钱
            money = money - createMoney;
            // 前几次的钱随机生成
            moneyMap.put(i, createMoney);
        }
        // 剩余的所有钱
        moneyMap.put(numberOfRandomCalculations, money);

        System.out.println(JSONObject.toJSONString(moneyMap));

        RedBus redBus = new RedBus(moneyMap);

        Thread t1 = new Thread(redBus,"壹号 1111");
        Thread t2 = new Thread(redBus,"贰号 2222222");
        Thread t3 = new Thread(redBus,"弎号 333333333");
        Thread t4 = new Thread(redBus,"四号 444444444444");
        Thread t5 = new Thread(redBus,"五号 555555555555555");

        // t1.setName("壹号 1111");
        // t2.setName("贰号 2222222");
        // t3.setName("弎号 333333333");
        // t4.setName("四号 444444444444");
        // t5.setName("五号 555555555555555");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

        // NyistThreadUtils.sleep(3000);

    }

    @Override
    public void run() {
        lock.lock();
        try {
            if (moneyMap.isEmpty()) {
                log.info("=====>>>没抢到,,,,,当前线程为: {} ", NyistThreadUtils.getThreadName());
            }
            Random random = new Random();
            int getKey = random.nextInt(3);
            // NyistThreadUtils.sleep(1000);
            if (moneyMap.containsKey(getKey)) {
                log.info("=====>>>当前线程为: {} , 获取到的红包key为: {} , 值为:{}",
                        NyistThreadUtils.getThreadName(), getKey, moneyMap.get(getKey)
                );
                moneyMap.remove(getKey);
            }
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println(e+""+e.getMessage());
        } finally {
            lock.unlock();
        }
    }
}
